package com.abaddon.view;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.abaddon.controller.AbaddonItemizedOverlay;
import com.abaddon.controller.AbaddonLocationListener;
import com.abaddon.controller.AbaddonPropertyChangeValuesHolder;
import com.abaddon.controller.Invalidator;
import com.abaddon.controller.PersonRemover;
import com.abaddon.controller.PlaceRemover;
import com.abaddon.controller.ServerCommunicationRunnable;
import com.abaddon.controller.YesNoChoiceController;
import com.abaddon.model.Tag;
import com.abaddon.model.TagManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;

public class Abaddon extends MapActivity implements PropertyChangeListener{
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		showNotification("Voff!", "Abaddon", "Making maps a little more useful and a little more fun");
		setContentView(R.layout.main);
		TagManager.init(this);
		
//		TagManager.updateTag("Hubben", 57688372,11978943);
		
		// GPS-stuff
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		LocationListener locationListener = new AbaddonLocationListener(this);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 1, locationListener);
		
		//Thread - Server communication
		ServerCommunicationRunnable serverCom = new ServerCommunicationRunnable();
		Thread serverThread = new Thread(serverCom);
		serverThread.start();
		
		//Get lastKnownLocation
		String provider = locationManager.getBestProvider(new Criteria(), true);
		if(provider != null){
			Location location = locationManager.getLastKnownLocation(provider);
			if(location != null){
				int latitude = (int)(location.getLatitude()*Math.pow(10, 6));
				int longitude = (int)(location.getLongitude()*Math.pow(10, 6));
				TagManager.updatePerson(TagManager.getUserName(), latitude, longitude);
			}
		}
		
	}
	/**
	 * Shows the lion in the topmost titlebar when the application is running
	 * @param tickerText
	 * @param contentTitle
	 * @param contentText
	 */
	public void showNotification(String tickerText, String contentTitle, String contentText){
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		int icon = R.drawable.icon;
		//long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, 0);
		Context context = getApplicationContext();
		Intent notificationIntent = new Intent(this, Abaddon.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Notification.FLAG_ONGOING_EVENT);
		notification.flags = Notification.FLAG_ONGOING_EVENT;
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		int HELLO_ID = 1;
		mNotificationManager.notify(HELLO_ID, notification);
	}

	public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.main_menu, menu);
    	return true;
    }
     
    public boolean onOptionsItemSelected(MenuItem item){

    	//Handle item selection
    	switch (item.getItemId()){
   		case R.id.settings:
   			startActivity(new Intent("com.abaddon.view.SETTINGSVIEW"));
   			return true;
   		case R.id.help:
   			startActivity(new Intent("com.abaddon.view.HELPVIEW"));
   			return true;
   		case R.id.about:
   			startActivity(new Intent("com.abaddon.view.ABOUTVIEW"));
   			return true;
   		default:
   			return super.onOptionsItemSelected(item);
    	}
    }
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_SEARCH){
			setTitleColor(Color.rgb((int)(Math.random()*255), (int)(Math.random()*255), (int)(Math.random()*255)));
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	public Abaddon() { }       

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		
		Log.i("TESTING LONGPRESS", "PROPERTY CHANGE RECEIVED");

		if(event.getPropertyName().equals(AbaddonPropertyChangeValuesHolder.LONGPRESS)){
			Log.i("Preparing to start runOnUiThread", "WORKS");
			runOnUiThread(new YesNoChoiceController(this, (GeoPoint)event.getNewValue()));
		}
		if(event.getPropertyName().equals(AbaddonPropertyChangeValuesHolder.INVALIDATE)){
			runOnUiThread(new Invalidator());
		}
//		if(event.getPropertyName().equals(AbaddonPropertyChangeValuesHolder.REMOVEALLPERSONS)){
//			runOnUiThread(new AllPersonRemover());
//		}
		if(event.getPropertyName().equals(AbaddonPropertyChangeValuesHolder.REMOVEPLACE)){
			runOnUiThread(new PlaceRemover((Tag)event.getNewValue(), (AbaddonItemizedOverlay)event.getOldValue()));
		}
		if(event.getPropertyName().equals(AbaddonPropertyChangeValuesHolder.REMOVEPERSON)){
			runOnUiThread(new PersonRemover((Tag)event.getNewValue(), (AbaddonItemizedOverlay)event.getOldValue()));
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
		android.os.Process.killProcess(android.os.Process.myPid());
	}
	
}